package com.itheima.wechat;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfoVo;
import com.itheima.service.OrderService;
import com.itheima.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    JedisUtil jedisUtil;

    //failover 出错会重试（默认重试2次）

    //failfast 出错不在调用

    //幂等性
    @Reference(cluster = "failfast")
    OrderService orderService;

    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderInfoVo orderInfoVo){
        String token = orderInfoVo.getToken();
        if(token == null){
            return Result.error("非法请求");
        }

        //200请求都带着41b6b2a8-4c61-4471-a3a5-7198bf440005
//        Long count = jedisUtil.delete(token); //单线程 删除请求都要排队
//        if(count == 0){
//            return Result.error("非法请求,删除token失败");
//        }


        //校验验证码
        String validateCode = orderInfoVo.getValidateCode();
        String telephone = orderInfoVo.getTelephone();
        String redisCode = jedisUtil.get(telephone + "001");

        if(redisCode == null || !redisCode.equals(validateCode)){
            return Result.error("验证码错误");
        }

        //把预约类型改为 微信预约
        orderInfoVo.setOrderType(Order.ORDERTYPE_WEIXIN);
        //调用service下单
        Result result = null;
        int count = 0;
        try {
            result = orderService.submit(orderInfoVo);
        } catch (Exception e) {
            e.printStackTrace();
//           while (count < 3){
//               orderService.submit(orderInfoVo);
//               count ++;
//           }
        }

        if(result.isFlag()){
            //预约成功要给用户发送短信提示
        }

        return result;

    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        Map map = orderService.findById(id);

        return Result.success("",map);
    }

    @RequestMapping("/getToken")
    public Result getToken(){
        String token = UUID.randomUUID().toString();
        jedisUtil.add(token,500 ,token);
        return Result.success("",token);
    }

}
